import { useEffect, useMemo, useRef, useState, useCallback } from 'react';
import { pinyin } from 'pinyin-pro';
import { useNavigate } from 'react-router-dom';

import { SEARCH } from '@/config/url';
import { getCategoryList } from '@/service/api';
import styles from './index.module.scss';

export default () => {
  const [list, setList] = useState([]);
  const [activeLetter, setActiveLetter] = useState('');
  const containerRef = useRef(null);
  const navigate = useNavigate();

  // 26个大写字符
  const letters = Array.from({ length: 26 }, (_, i) => String.fromCharCode(65 + i));

  // 获取字符首字符对应字母
  const getFirstCharLetter = (str) => {
    if (!str) return '';
    const firstChar = str.charAt(0);
    // 只对第一个字符取拼音首字母
    return pinyin(firstChar, { pattern: 'first' }).toUpperCase();
  }

  const toSearch = obj => {
    const usp = new URLSearchParams();
    usp.set('type', 'category');
    usp.set('q', obj.name);

    // 跳转到搜索页面
    navigate(`${SEARCH}?${usp.toString()}`);
  };
  // 请求分类数据，并格式化数据
  const getData = async () => {
    const [res, err] = await getCategoryList({pageNo: 1, pageSize: 9999});
    if (err) return;

    const items = (res.data?.records || []).map((row) => {
      const name = row?.categoryName || '';
      const item = {
        categoryId: row.id,
        name,
        icon: (row.categoryImages||'').split(',').filter(Boolean)[0] || '/images/image-holder.svg',
      };
      return item;
    });

    setList(items);
  };
  useEffect(() => {
    getData();
  }, []);


  return (
    <div className={styles['category-wrap']}>
      <div className={styles['category-container']} ref={containerRef}>
        {(list || []).map((item, index) => (
          <div className={styles['section']} key={item.categoryId}>
              <div className={styles['item']} onClick={toSearch.bind(null, item)}>
                <div className={styles['item-icon']}>
                  <img src={item.icon ? `${item.icon}` : '/images/image-holder.svg'} alt={item.name} />
                </div>
                <div className={styles['item-name']}>{item.name}</div>
              </div>
          </div>
        ))}
      </div>

    </div>
  );
}
